package com.tcfvic.client.panels.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.tcfvic.client.PersonService;
import com.tcfvic.client.PersonServiceAsync;
import com.tcfvic.client.panels.widgets.addons.advancedtable.AdvancedTable;
import com.tcfvic.client.panels.widgets.addons.advancedtable.RowSelectionListener;
import com.tcfvic.client.pojos.Jsp;
import com.tcfvic.client.tools.State;
import com.tcfvic.client.tools.Tools;

public class JSPDetailsInputWidget extends FlexTable implements
		RowSelectionListener {

	private TextBox jspId = new TextBox();
	private TextBox nameTextBox = new TextBox();
	private TextBox phoneTextBox = new TextBox();
	private TextBox streetLine1 = new TextBox();
	private TextBox streetLine2 = new TextBox();
	private TextBox suburb = new TextBox();
	private ListBox state = null;
	private TextBox postcode = new TextBox();
	private TextArea notes = new TextArea();
	private TextBox website = new TextBox();
	private JSPDetailsListWidget list = null;

	private final PersonServiceAsync personService = GWT
			.create(PersonService.class);

	public JSPDetailsInputWidget() {
		super();

		// Create a table to layout the form options
		setCellSpacing(4);
		setWidth("100%");

		// Add some standard form options
		int rowNum = 0;
		setHTML(rowNum, 0, "JSAP name");
		setWidget(rowNum, 1, nameTextBox);
		setHTML(rowNum, 2, "Phone number");
		setWidget(rowNum++, 3, phoneTextBox);

		setHTML(rowNum, 0, "Street");
		setWidget(rowNum, 1, streetLine1);
		setHTML(rowNum, 2, "Email");
		setWidget(rowNum++, 3, streetLine2);
		setHTML(rowNum, 0, "Suburb");
		setWidget(rowNum, 1, suburb);
		setHTML(rowNum, 2, "Website");
		setWidget(rowNum++, 3, website);
		setHTML(rowNum, 0, "State");
		state = getStatesListBox();
		setWidget(rowNum++, 1, state);
		setHTML(rowNum, 0, "Postcode");
		setWidget(rowNum++, 1, postcode);
		setHTML(rowNum, 0, "Notes");
		setWidget(rowNum++, 1, notes);

		final Button saveButton = new Button("Save");
		saveButton.getElement().setId("saveButton");
		setWidget(rowNum, 3, saveButton);

		// Add a handler to close the DialogBox
		saveButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				saveJSPDetails();
			}
		});

	}

	private boolean minimumInput() {
		if (nameTextBox.getText() == null
				|| nameTextBox.getText().trim().length() == 0) {
			new SimpleMessagePopup("Please enter a JSP name", nameTextBox)
					.showPopup();
			return false;
		}
		return true;
	}

	public void createNewRecord() {
		clearAllFields();
		jspId.setText("");
	}
	
	public void clearAllFields() {
		jspId.setText("-1");
		nameTextBox.setText("");
		streetLine1.setText("");
		streetLine2.setText("");
		suburb.setText("");
		postcode.setText("");
		notes.setText("");
		phoneTextBox.setText("");
		website.setText("");
		Tools.resetList(state);
	}

	public ListBox getStatesListBox() {
		final ListBox dropBox = new ListBox(false);

		dropBox.addItem("");
		for (State state : State.values()) {
			dropBox.addItem(state.getState());
		}
		return dropBox;
	}

	@Override
	public void onRowSelected(AdvancedTable sender, String rowId) {
		clearAllFields();
		personService.getJSPDetails(Integer.valueOf(rowId),
				new AsyncCallback<Jsp>() {
					@Override
					public void onSuccess(Jsp jsp) {
						jspId.setText(String.valueOf(jsp.getId()));
						nameTextBox.setText(jsp.getName());
						phoneTextBox.setText(jsp.getPhone());
						notes.setText(jsp.getNotes());
						streetLine1.setText(jsp.getStreet());
						streetLine2.setText(jsp.getStreet2());
						suburb.setText(jsp.getSuburb());
						website.setText(jsp.getWebsite());
						if (jsp.getState() != null
								&& jsp.getState().trim().length() > 0) {
							state.setSelectedIndex(State
									.valueOf(jsp.getState()).getId());
						}
						postcode.setText(jsp.getPostcode() != null ? jsp
								.getPostcode().toString() : "");
					}

					@Override
					public void onFailure(Throwable caught) {
						System.err
								.println("Error occured returning the JSP details: "
										+ caught);
						new SimpleMessagePopup(
								"The JSP record was not retrieved due to an internal error",
								null).showPopup();
					}
				});
	}

	private void saveJSPDetails() {
		try {
			if (!minimumInput()) {
				return;
			}

			Jsp jsp = new Jsp();
			if (jspId != null && jspId.getText().trim().length() > 0) {
				jsp.setId(new Integer(jspId.getText()));
			}

			jsp.setName(nameTextBox.getText());
			jsp.setPhone(phoneTextBox.getText());
			jsp.setNotes(notes.getText());

			jsp.setStreet(streetLine1.getText());
			jsp.setStreet2(streetLine2.getText());
			jsp.setSuburb(suburb.getText());
			jsp.setWebsite(website.getText());
			if (state != null && state.getSelectedIndex() > -1) {
				jsp.setState(state.getItemText(state.getSelectedIndex()));
			}
			if (postcode.getText() != null && !postcode.getText().isEmpty()) {
				jsp.setPostcode(new Integer(postcode.getText()));
			}

			personService.saveJSPDetails(jsp, new AsyncCallback<Void>() {
				@Override
				public void onSuccess(Void result) {
					System.out
							.println("Successfully wrote JSP record to dbase");
					clearAllFields();
					if (list != null) {
						list.updateTableData();
					}
					new SimpleMessagePopup("JSP saved successfully", null)
							.showPopup();
				}

				@Override
				public void onFailure(Throwable caught) {
					System.err
							.println("Error occured writing JSP details to database in "
									+ "CompanyDetailsInputWidget.saveJSPDetail: "
									+ caught);
					new SimpleMessagePopup(
							"The data was not saved due to an internal error",
							null).showPopup();
				}
			});
		} catch (Exception e) {
			new SimpleMessagePopup("An error occured saving the JSP details: "
					+ e, null).showPopup();
		}
	}

	public void addJSPDetailsList(JSPDetailsListWidget list) {
		this.list = list;
	}

}
